﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using IdentityMine.Windows.Eventing;

namespace SilverlightEventing.IdentityMine.Windows.Eventing
{
    public class RoutedEventHandlerData
    {
        public RoutedEventHandlerData(RoutedEventEx routedEvent, UIElement uiElement, Delegate handler, bool handledEventsToo)
        {
            this.Handler = handler;
            this.HandledEventsToo = handledEventsToo;
            this.UIElement = uiElement;
            this.RoutedEvent = routedEvent;
        }

        private WeakReference _routedEvent;

        public RoutedEventEx RoutedEvent
        {
            get
            {
                RoutedEventEx ret = null;
                if (_routedEvent.IsAlive)
                {
                    ret = (_routedEvent.Target as RoutedEventEx);
                }

                return ret;
            }
            set
            {
                _routedEvent = new WeakReference(value);
            }
        }

        private WeakReference _uiElement;

        public UIElement UIElement
        {
            get
            {
                UIElement ret = null;

                if (_uiElement.IsAlive)
                {
                    ret = (_uiElement.Target as UIElement);
                }

                return ret;
            }
            protected set { _uiElement = new WeakReference(value); }
        }

        private WeakReference _handler;

        public Delegate Handler
        {
            get {
                Delegate ret = null;

                if (_handler.IsAlive)
                {
                    ret = (_handler.Target as Delegate);
                }
                return ret; 
            }
            protected set { _handler = new WeakReference(value); }
        }

        private bool _handledEventsToo = false;

        public bool HandledEventsToo
        {
            get { return _handledEventsToo; }
            set { _handledEventsToo = value; }
        }

        public void InvokeEventHandler(object target, RoutedEventArgsEx routedEventArgs)
        {
            if (routedEventArgs.Handled == false || HandledEventsToo == true)
            {
                if (Handler is RoutedEventHandlerEx)
                {
                    (Handler as RoutedEventHandlerEx)(target, routedEventArgs);
                }
                else
                {
                    routedEventArgs.InvokeEventHandler(Handler, target);
                }
            }
        }
    }
}
